<?php

namespace app\common\service\GoodsClassService;

use app\common\service\GoodsService\ChannelEsService;
use app\common\service\RequestService\Http;
use app\model\BbcModel\BusinessGoods;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsSupplyClass;
use app\model\BbcModel\GoodsBrand;
use app\Normal;
use think\facade\Db;

class GoodsClassService
{
    /**
     * 商品分类列表
     * @param $param
     * @return array
     */
    public function goodsClassLists($param): array
    {
        $data_lists = GoodsClass::instance()->lists(['cid'=>$param['cid'],'df'=>0,'_order_'=>'sort desc,id desc','_fields_'=>'id,pid,name,icon,show,sort']);
        $tree_lists = tree($data_lists,0,'id','pid');
        if(count($tree_lists) <= 0){
            $tree_lists = $data_lists;
        }
        return Normal::returnCode(Normal::SUC, '获取成功',$tree_lists);
    }

    /**
     * 全部商品分类列表（用于下拉框筛选）
     * @param $param
     * @return array
     */
    public function allGoodsClassLists($param): array
    {
        $data_lists = GoodsClass::instance()->lists(['cid'=>$param['cid'],'df'=>0,'_order_'=>'sort desc,id desc','_fields_'=>'id,pid,name']);
        $tree_lists = tree($data_lists,0,'id','pid');
        if(count($tree_lists) <= 0){
            $tree_lists = $data_lists;
        }
        return Normal::returnCode(Normal::SUC, '获取成功',$tree_lists);
    }

    /**
     * @param $param
     * @return array
     */
    public function addGoodsClass($param): array
    {
        if(!$param['name']){
            return Normal::returnCode(Normal::FAIL,'分类名称不能为空');
        }
        if($param['pid'] < 0 || !is_numeric($param['pid'])){
            return Normal::returnCode(Normal::FAIL,'上级分类ID非法');
        }
        $u = GoodsClass::instance()->info(['name'=>$param['name'],'cid'=>$param['cid'],'df'=>0]);
        if($u){
            return Normal::returnCode(Normal::FAIL,'分类名称已存在');
        }
        if($param['pid'] > 0){ //新增非顶级分类
            $s = GoodsClass::instance()->info(['id'=>$param['pid'],'cid'=>$param['cid'],'df'=>0]);
            if(!$s){
                return Normal::returnCode(Normal::FAIL,'父级分类不存在');
            }
            /*if($s['pid'] != 0){
                return Normal::returnCode(Normal::FAIL,'当前选择父级为非顶级分类，最多选择第2级分类');
            }*/
        }
        if(!isset($param['sort']) || !$param['sort']){
            $param['sort'] = 0;
        }
        if(!isset($param['icon'])){
            $param['icon'] = '';
        }
        if(!isset($param['show'])){
            $param['show'] = 1;
        }
        $res = GoodsClass::instance()->add(['name'=>$param['name'],'icon'=>$param['icon'],'sort'=>$param['sort'],'pid'=>$param['pid'],'cid'=>$param['cid'],'cb_id'=>$param['cb_id'],'']);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    /**
     * @param $param
     * @return array
     */
    public function goodsClassInfo($param): array
    {
        if(!$param['id']){
            return Normal::returnCode(Normal::FAIL,'分类ID不能为空');
        }
        $info = GoodsClass::instance()->info(['cid'=>$param['cid'],'id'=>$param['id'],'df'=>0,'_fields_'=>'id,pid,name,icon,show,sort']);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'分类不存在');
        }
        return Normal::returnCode(Normal::SUC,'获取成功',$info);
    }

    /**
     * @param $param
     * @return array
     */
    public function editGoodsClass($param): array
    {
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'分类ID不能为空');
        }
        if(!$param['name']){
            return Normal::returnCode(Normal::FAIL,'分类名称不能为空');
        }
        if($param['pid'] < 0 || !is_numeric($param['pid'])){
            return Normal::returnCode(Normal::FAIL,'上级分类ID非法');
        }
        $u = Db::table('goods_class')->where(['cid'=>$param['cid'],'name'=>$param['name'],'df'=>0])->where('id','<>',$param['id'])->find();
        if($u){
            return Normal::returnCode(Normal::FAIL,'分类名称已存在');
        }
        if(!GoodsClass::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']])){
            return Normal::returnCode(Normal::FAIL,'分类不存在');
        }
        if($param['pid'] > 0){ //编辑非顶级分类
            $s = GoodsClass::instance()->info(['id'=>$param['pid'],'cid'=>$param['cid']]);
            if(!$s){
                return Normal::returnCode(Normal::FAIL,'父级分类不存在');
            }
            if($s['pid'] != 0){
//                return Normal::returnCode(Normal::FAIL,'当前选择父级为非顶级分类，最多选择第2级分类');
            }
        }
        if(!$param['sort']){
            $param['sort'] = 99;
        }
        if(!isset($param['show'])){
            $param['show'] = 1;
        }
        if(!isset($param['icon'])){
            $param['icon'] = '';
        }
        $res = GoodsClass::instance()->edit(['id'=>$param['id']],['name'=>$param['name'],'icon'=>$param['icon'],'sort'=>$param['sort'],'pid'=>$param['pid'],'show'=>$param['show']]);
        if($res === false){
            return Normal::returnCode(Normal::FAIL,'修改失败');
        }
        return Normal::returnCode(Normal::SUC,'修改成功');
    }

    /**
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delGoodsClass($param): array
    {
        $class = GoodsClass::instance()->info(['id'=>$param['id'],'cb_id'=>$param['cb_id'],'cid'=>$param['cid'],'df'=>0]);
        if(!$class){
            return Normal::returnCode(Normal::FAIL,'商品分类不存在');
        }
        $class_ids = GoodsClass::instance()->where(['pid'=>$class['id'],'df'=>0])->column('id');
        array_push($class_ids, $class['id']);
        if(Goods::instance()->where('class_id','in',$class_ids)->where(['df' =>0, 'cid' =>$param['cid']])->find()){
            return Normal::returnCode(Normal::FAIL,'该分类下存在商品，暂不能删除，请变更其分类后，再删除');
        }
        $res = GoodsClass::instance()->edit(['id'=>$param['id']],['df'=>1]);
        if($res == false){
            return Normal::returnCode(Normal::FAIL,'删除失败');
        }
        return Normal::returnCode(Normal::SUC,'删除成功');
    }

    /**
     * @param $param
     * @return array
     */
    public function resetGoodsClass($param): array
    {
        $apiUrl = env('yc_classify_url');
        if(!$apiUrl){
            return Normal::returnCode(Normal::FAIL,'云仓分类请求地址未配置');
        }
        if(GoodsClass::instance()->info(['cid'=>$param['cid']])){
            return Normal::returnCode(Normal::FAIL,'已初始化过商品分类');
        }
        Db::startTrans();
        try{
            $res = Http::post($apiUrl, '', ['Content-Type:application/json','systemID:s2b']);
            $classData = json_decode($res,true);
            $classData=$classData['data'];
            if(!$classData){
                return Normal::returnCode(Normal::FAIL,'没有分类');
            }
            foreach($classData as $key=>$value){
                $goods_classinsertdata['cid'] = $param['cid'];
                $goods_classinsertdata['cb_id'] = $param['cb_id'];
                if(!$value['name']){
                    $value['name'] = '';
                }
                $goods_classinsertdata['name'] = $value['name'];
                if(empty($value['imageUrls'][0])){
                    $value['imageUrls'][0] = '';
                }
                $goods_classinsertdata['icon'] = $value['imageUrls'][0] ?? '';
                $goods_classinsertdata['pid'] = 0;
                $goods_classinsertdata['cd'] = time();
                $newClassId = GoodsClass::instance()->add($goods_classinsertdata);
                $children_class = $value['list'];
                if($children_class){
                    foreach($children_class as $k=>$v){
                        $childrenClassInsert['cid'] = $param['cid'];
                        if(!$v['name']){
                            $v['name'] = '';
                        }
                        $childrenClassInsert['name'] = $v['name'];
                        if(empty($v['imageUrls'][0])){
                            $v['imageUrls'][0] = '';
                        }
                        $childrenClassInsert['icon'] = $v['imageUrls'][0] ?? '';
                        $childrenClassInsert['pid'] = $newClassId;
                        $childrenClassInsert['cd'] = time();
                        $childrenClassInsert['cb_id'] = $param['cb_id'];
                        GoodsClass::instance()->add($childrenClassInsert);
                    }
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return Normal::returnCode(Normal::FAIL,'初始化分类失败');
        }
        return Normal::returnCode(Normal::SUC,'初始化分类成功');
    }

    /**
     * @param $param
     * @return array
     */
    public function oneGoodsClass($param): array
    {
        $data_lists = GoodsClass::instance()->lists(['cid'=>$param['cid'],'pid'=>0,'df'=>0,'_fields_'=>'id,name','_order_'=>'sort desc,id desc']);
        return Normal::returnCode(Normal::SUC,'获取成功',$data_lists);
    }

    /**
     * @param $param
     * @return array[]
     */
    public function makeWhere($param): array
    {
        $where = [
            ['cid','=',$param['cid']],
        ];
        if(isset($param['supply_class_name']) && $param['supply_class_name'] != ''){ //供应商分类
            $where[] = ['name','in',$param['supply_class_name']];
        }
        if(isset($param['class_ids']) && $param['class_ids']){ //渠道分类
            $children = GoodsClass::instance()->where('pid','in',$param['class_ids'])->where(['cid'=>$param['cid'],'df'=>0,'show'=>1])->column('id');
            $ids_arr = $param['class_ids'];
            foreach($ids_arr as $v){
                array_push($children, $v);
            }
            $class_ids = implode(',', $children);
            $where[] = ['class_id','in',$class_ids];
        }
        if(isset($param['is_relevance']) && $param['is_relevance'] == 1){ //已关联渠道分类
            $where[] = ['class_id','<>',0];
        }else if(isset($param['is_relevance']) && $param['is_relevance'] == 0){ //未关联
            $where[] = ['class_id','=',0];
        }
        return $where;
    }

    /**
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function relevanceLists($param): array
    {
        $page = (isset($param['page']) && !empty($param['page'])) ? $param['page'] : 1;
        $limit = (isset($param['limit']) && !empty($param['limit'])) ? $param['limit'] : 20;
        $where = $this->makeWhere($param);
        $data_lists = GoodsSupplyClass::instance()->where($where)->field('id,name,class_id,supply_id')->order('id desc')->limit((int)$limit)->page((int)$page)->select()->each(function($item,$key) use($param){
            $item['goods_num'] = Goods::instance()->where(['supply_class_id'=>$item['id'],'cid'=>$param['cid'],'df'=>0])->count();
            $item['status_name'] = $item['class_id'] == 0 ? '否' : '是';
            if($item['class_id']){
                $item['class_id_name'] = GoodsClass::instance()->where(['cid'=>$param['cid'],'id'=>$item['class_id']])->value('name');
            }else{
                $item['class_id_name'] = '';
            }
            return $item;
        });
        $total =  GoodsSupplyClass::instance()->where($where)->count();
        return Normal::returnCode(Normal::SUC,'获取成功',['data_lists'=>$data_lists,'total'=>$total]);
    }

    /**
     * @param $param
     * @return array
     */
    public function supplierGoodsClass($param): array
    {
        $data_lists = GoodsSupplyClass::instance()->lists(['cid' =>$param['cid'],'_fields_'=>'id,name']);
        return Normal::returnCode(Normal::SUC,'获取成功',$data_lists);
    }

    /**
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function subRelevance($param): array
    {
        if(!isset($param['supply_class_name']) || !$param['supply_class_name']){
            return Normal::returnCode(Normal::FAIL,'请选择供应商分类');
        }
        if(!isset($param['class_id']) || !$param['class_id']){
            return Normal::returnCode(Normal::FAIL,'请选择渠道分类');
        }
        if(!GoodsClass::instance()->where(['id'=>$param['class_id'],'df'=>0])->where('pid','<>',0)->find()){
            return Normal::returnCode(Normal::FAIL,'渠道分类不能选择顶级分类');
        }
        $supply_class = GoodsSupplyClass::instance()->where(['cid'=>$param['cid']])->where('name','in',$param['supply_class_name'])->select()->toArray();//供应商分类
        if(!$supply_class){
            return Normal::returnCode(Normal::FAIL,'供应商分类不存在');
        }
        $new_supply_class = [];
        $new_goods_class = [];
        foreach($supply_class as $k=>$v){
            $new_supply_class[] = ['id'=>$v['id'],'class_id'=>$param['class_id']];
            $new_goods_class[] = $v['id'];
        }
        $ChannelEsService = new ChannelEsService();
        Db::startTrans();
        try{
            GoodsSupplyClass::instance()->saveAll($new_supply_class);
            Goods::instance()->where(['cid'=>$param['cid']])->where('supply_class_id','in',$new_goods_class)->update(['class_id'=>$param['class_id']]);

            $goodsList = Goods::instance()->lists(['class_id'=>$param['class_id'],'cid'=>$param['cid'],'df'=>0,'_fields_'=>'id,name,brand_id,status']);
            if($goodsList){
                $brandList = Goodsbrand::instance()->lists(['_fields_'=>'id,name']);
                $brandList = array_column($brandList,'name','id');
                $ids = array_column($goodsList,'id');
                $goodsIndex = array_column($goodsList,null,'id');
                $channelInsert = [];
                $businessGoods = BusinessGoods::instance()->lists([['goods_id','in',$ids],'_fields_'=>'id,level_id,goods_id']);
                foreach ($businessGoods as $v){
                    $updateIndexData['id']         = $v['id'];
                    $updateIndexData['goodsId']    = $v['goods_id'];
                    $updateIndexData['name']       = $goodsIndex[$v['goods_id']]['name'];
                    $updateIndexData['classifyID'] = $param['class_id'];
                    $updateIndexData['channelID']  = $v['level_id'];
                    $updateIndexData['brandName']  = $brandList[$goodsIndex[$v['goods_id']]['brand_id']];
                    $updateIndexData['isActive']   = $goodsIndex[$v['goods_id']]['status'] ? true : false;
                    $channelInsert[]               = $updateIndexData;
                }
                if(!empty($channelInsert)){
                    $ChannelEsService->pushNew($channelInsert,'channel','insert');
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return Normal::returnCode(Normal::FAIL,'操作失败'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    /**
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function delRelevance($param): array
    {
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'供应商分类ID不能为空');
        }
        $info = GoodsSupplyClass::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'供应商分类不存在');
        }
        $goods_num = Goods::instance()->where(['supply_class_id'=>$param['id'],'cid'=>$param['cid'],'df'=>0])->count();
        if($goods_num > 0){
            return Normal::returnCode(Normal::FAIL,'当前供应商分类下有商品');
        }
        $res = GoodsSupplyClass::instance()->where(['id'=>$param['id']])->delete();
        if($res === false){
            return Normal::returnCode(Normal::FAIL,'删除失败');
        }
        return Normal::returnCode(Normal::SUC,'删除成功');
    }
}